package com.ruoyi.business.ajax;

import com.ruoyi.business.ajax.request.BasicRequest;
import com.ruoyi.business.ajax.request.DateRequest;
import com.ruoyi.business.ajax.request.PayRequest;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.business.utils.PayUtil;
import com.ruoyi.business.utils.TeamUtil;
import com.ruoyi.common.annotation.AjaxLogin;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.utils.DictUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@AjaxLogin
@RestController
@RequestMapping("/ajax/member")
public class AjaxMemberController extends AuthController {

    @Resource
    private IBizMemberService bizMemberService;

    @Resource
    private IBizMemberAddressService bizMemberAddressService;

    @Resource
    private IBizAccountService bizAccountService;

    @Resource
    private IBizTeamRewardService bizTeamRewardService;

    @Resource
    private IBizOrderService bizOrderService;

    @Resource
    private IBizCashInfoService bizCashInfoService;

    @Resource
    private IBizCashConfigService bizCashConfigService;

    @Resource
    private IBizPayOrderService bizPayOrderService;

    //个人中心
    @PostMapping("/center")
    public AjaxResult center()
    {
        Long userID = getUserID();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        BizMember member = bizMemberService.selectBizMemberById(userID);
        resultMap.put("name", member.getMemberName());
        resultMap.put("mobile", member.getMobile());
        resultMap.put("douBalance", member.getDouBalance());
        resultMap.put("douPerson", member.getDouPerson());
        resultMap.put("douTeam", member.getDouTeam());
        resultMap.put("douSpecial", member.getDouSpecial());
        resultMap.put("douField", member.getDouField());
        int specialLimit = Integer.parseInt(DictUtils.getDictLabel("busi_award_set", "7"));
        if (member.getDouSpecial() < specialLimit) {
            //判断复购提醒
            long buyNum = bizOrderService.selectBuyNum(userID);
            if (buyNum < 3) {
                resultMap.put("buyTip", "1");
            }
        }
        return AjaxResult.success(resultMap);
    }

    //个人中心
    @PostMapping("/accountDetail")
    public AjaxResult accountDetail()
    {
        Long userID = getUserID();
        BizAccountDetail detail = new BizAccountDetail();
        detail.setMemberId(userID);
        return AjaxResult.success(bizAccountService.selectBizAccountDetailList(detail));
    }

    //读取省份地区
    @PostMapping("/areaList")
    public AjaxResult areaList()
    {
        List<Map> list = bizMemberService.selectAreas();
        List<Map> result = new ArrayList<>();
        Map temp = new HashMap();
        for (Map item : list) {
            Long pid = (Long) item.get("parent_id");
            Integer lv = (Integer) item.get("level_type");
            if (lv.equals(1)) {
                result.add(item);
            } else {
                List<Map> children = (List<Map>) temp.get(pid);
                if (children == null) {
                    children = new ArrayList<>();
                }
                children.add(item);
                temp.put(pid, children);
            }
        }
        for (Map item : list) {
            Long id = (Long) item.get("id");
            List<Map> children = (List<Map>) temp.get(id);
            if (children != null) {
                item.put("children", children);
            }
        }
        return AjaxResult.success(result);
    }

    //读取我的地址列表
    @PostMapping("/addressList")
    public AjaxResult addressList()
    {
        Long userID = getUserID();
        return AjaxResult.success(bizMemberAddressService.selectBizMemberAddressList(userID));
    }

    //我的地址详细
    @PostMapping("/addressDetail")
    public AjaxResult addressDetail(@RequestBody BasicRequest request)
    {
        Long userID = getUserID();
        BizMemberAddress address = bizMemberAddressService.selectBizMemberAddressById(request.getId());
        if (address == null || !userID.equals(address.getMemberID())) {
            return AjaxResult.warn("操作有误请重试");
        }
        return AjaxResult.success(address);
    }

    //编辑我的地址
    @PostMapping("/addressEdit")
    public AjaxResult addressDetail(@RequestBody BizMemberAddress request)
    {
        Long userID = getUserID();
        BizMemberAddress address = bizMemberAddressService.selectBizMemberAddressById(request.getId());
        if (address == null || !userID.equals(address.getMemberID())) {
            return AjaxResult.warn("操作有误请重试");
        }
        return AjaxResult.success(bizMemberAddressService.updateBizMemberAddress(request));
    }

    //添加我的地址
    @PostMapping("/addressAdd")
    public AjaxResult addressAdd(@RequestBody BizMemberAddress request)
    {
        Long userID = getUserID();
        request.setMemberID(userID);
        return AjaxResult.success(bizMemberAddressService.insertBizMemberAddress(request));
    }

    //删除我的地址
    @PostMapping("/addressDelete")
    public AjaxResult addressDelete(@RequestBody BasicRequest request)
    {
        Long userID = getUserID();
        BizMemberAddress address = bizMemberAddressService.selectBizMemberAddressById(request.getId());
        if (address == null || !userID.equals(address.getMemberID())) {
            return AjaxResult.warn("操作有误请重试");
        }
        if (bizMemberAddressService.selectBizMemberAddressList(userID).size() <= 1) {
            return AjaxResult.warn("不能删除默认收货地址");
        }
        return AjaxResult.success(bizMemberAddressService.deleteBizMemberAddressById(request.getId()));
    }

    //取出银行数据
    @PostMapping("/bankInfo")
    public AjaxResult bankInfo()
    {
        Map result = new HashMap();
        List<SysDictData> levels = DictUtils.getDictCache("busi_cashdraw_bank");
        for (SysDictData dict : levels) {
            result.put(dict.getDictValue(), dict.getDictLabel());
        }
        return AjaxResult.success(result);
    }

    //兑现设置列表
    @PostMapping("/configList")
    public AjaxResult configList()
    {
        Long userID = getUserID();
        BizCashConfig config = new BizCashConfig();
        config.setMemberId(userID);
        return AjaxResult.success(bizCashConfigService.selectBizCashConfigList(config));
    }

    //兑现设置详细
    @PostMapping("/configDetail")
    public AjaxResult configDetail(@RequestBody BasicRequest request)
    {
        Long userID = getUserID();
        BizCashConfig config = bizCashConfigService.selectBizCashConfigById(request.getId());
        if (config == null || !userID.equals(config.getMemberId())) {
            return AjaxResult.warn("操作有误请重试");
        }
        return AjaxResult.success(config);
    }

    //编辑兑现设置
    @PostMapping("/configEdit")
    public AjaxResult configEdit(@RequestBody BizCashConfig request)
    {
        Long userID = getUserID();
        BizCashConfig config = bizCashConfigService.selectBizCashConfigById(request.getId());
        if (config == null || !userID.equals(config.getMemberId())) {
            return AjaxResult.warn("操作有误请重试");
        }
        return AjaxResult.success(bizCashConfigService.updateBizCashConfig(request));
    }

    //添加兑现设置
    @PostMapping("/configAdd")
    public AjaxResult configAdd(@RequestBody BizCashConfig request)
    {
        Long userID = getUserID();
        request.setMemberId(userID);
        return AjaxResult.success(bizCashConfigService.insertBizCashConfig(request));
    }

    //删除兑现设置
    @PostMapping("/configDelete")
    public AjaxResult configDelete(@RequestBody BasicRequest request)
    {
        Long userID = getUserID();
        BizCashConfig config = bizCashConfigService.selectBizCashConfigById(request.getId());
        if (config == null || !userID.equals(config.getMemberId())) {
            return AjaxResult.warn("操作有误请重试");
        }
        return AjaxResult.success(bizCashConfigService.deleteBizCashConfigById(request.getId()));
    }

    //团队信息
    @PostMapping("/teamInfo")
    public AjaxResult teamInfo()
    {
        Long userID = getUserID();
        Map result = new HashMap();
        result.put("dailyInfo", bizTeamRewardService.selectDailyTeamReward(userID));
        result.put("teamData", TeamUtil.getTeamData(bizMemberService, userID, null));
        List<Map> orderList = bizOrderService.selectTeamBizOrder(userID);
        result.put("teamOrders", orderList);
        List<Map> fiftyOrders = new ArrayList<>();
        int count = 0;
        for (Map order : orderList) {
            int pCount = (Integer) order.get("product_count");
            if (count + pCount > 50) {
                pCount = 50 - count;
            }
            Map item = new HashMap();
            item.put("member_name", order.get("member_name"));
            item.put("mobile", order.get("mobile"));
            item.put("create_time", order.get("create_time"));
            item.put("count", pCount);
            fiftyOrders.add(item);
            count += pCount;
            if (count >= 50) break;
        }
        result.put("fiftyOrders", fiftyOrders);
        return AjaxResult.success(result);
    }

    //团队分成每日信息
    @PostMapping("/dailyDetail")
    public AjaxResult dailyDetail(@RequestBody DateRequest request)
    {
        Long userID = getUserID();

        BizTeamReward reward = new BizTeamReward();
        reward.setMemberId(userID);
        reward.setRewardType(BizTeamReward.TEAM_REWARD_TYPE_TEAM);
        reward.setRewardDate(request.getDate());
        return AjaxResult.success(bizTeamRewardService.selectBizTeamRewardList(reward));
    }

    //提现信息
    @PostMapping("/getCashInfo")
    public AjaxResult getCashInfo()
    {
        Long userID = getUserID();
        int[] types = {BizAccount.DOU_FIELD, BizAccount.DOU_TEAM, BizAccount.DOU_PERSON};
        //福豆田分成限制
        float fieldRate = Float.parseFloat(DictUtils.getDictLabel("busi_cashdraw_set", "1")) / 100;
        Map resultMap = new HashMap();
        String timeLimit = DictUtils.getDictLabel("busi_cashdraw_set", "2");
        if (!DateUtils.isTimeInArea(timeLimit)) {
            resultMap.put("timeWarn", "提现时间为" + timeLimit);
        }
        BizCashConfig config = new BizCashConfig();
        config.setMemberId(userID);
        resultMap.put("cardList", bizCashConfigService.selectBizCashConfigList(config));
        Map typeMap = new HashMap();
        for (int type : types) {
            Map item = new HashMap();
            long dou = bizMemberService.selectBizMemberDou(userID, type);
            item.put("dou", dou);
            float rate = 1f;
            if (type == BizAccount.DOU_FIELD) {
                rate = fieldRate;
            }
            item.put("rate", rate);
            double maxCash = Math.floor(dou * rate);
            item.put("maxCash", maxCash);
            typeMap.put(type, item);
        }
        resultMap.put("types", typeMap);
        return AjaxResult.success(resultMap);
    }

    //添加提现申请
    @PostMapping("/addCashInfo")
    public AjaxResult addCashInfo(@RequestBody BizCashInfo bizCashInfo)
    {
        Long userID = getUserID();
        if (true) {
            return AjaxResult.warn("系统维护中,无法进行提现操作");
        }
        long douSpecial = bizMemberService.selectBizMemberDou(userID, BizAccount.DOU_SPECIAL);
        if (douSpecial == 0) {
            return AjaxResult.warn("该账户已经无效,无法进行提现操作");
        }
        String timeLimit = DictUtils.getDictLabel("busi_cashdraw_set", "2");
        if (!DateUtils.isTimeInArea(timeLimit)) {
            return AjaxResult.warn("提现时间错误");
        }
        Calendar now = Calendar.getInstance();
        if (now.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            return AjaxResult.warn("星期日暂停提现");
        }
        //检查金额
        if (bizCashInfo.getDrawMoney() <= 0 || bizCashInfo.getDrawMoney() % 100 != 0) {
            return AjaxResult.warn("兑现金额错误");
        }
        if (bizCashInfo.getDrawMoney() < 200) {
            return AjaxResult.warn("兑现金额最小200");
        }
        bizCashInfo.setMemberId(userID);
        bizCashInfo.setStatus(BizCashInfo.CASH_INFO_STATUS_INITIAL);
        return bizCashInfoService.addCashInfo(bizCashInfo);
    }

    //我的提现信息列表
    @PostMapping("/listCashInfo")
    public AjaxResult listCashInfo()
    {
        Long userID = getUserID();

        BizCashInfo cashInfo = new BizCashInfo();
        cashInfo.setMemberId(userID);
        return AjaxResult.success(bizCashInfoService.selectBizCashInfoList(cashInfo));
    }

    //充值
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody PayRequest request)
    {
        Long userID = getUserID();
        if (true) {
            return AjaxResult.warn("系统维护中,无法进行充值操作");
        }
        String plat = request.getPlat();
        Long money = request.getMoney();
        BizPayOrder payOrder = new BizPayOrder();
        payOrder.setMemberId(userID);
        payOrder.setTradePlat(request.getPlat());
        String tradeNo = DateUtils.getMilliTime();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTradeNum(new BigDecimal(money));
        payOrder.setTradeState(0);

        Map result = null;
        //支付宝支付
        if ("zfb".equals(plat)) {
            String form = null;
            try {
                form = PayUtil.alipay(tradeNo, money + "福豆", money);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (form == null) {
                return AjaxResult.warn("支付出现问题, 请联系管理员");
            }
            payOrder.setZfbForm(form);
            bizPayOrderService.insertBizPayOrder(payOrder);
            result = new HashMap();
            result.put("plat", plat);
            result.put("id", payOrder.getId());
            return AjaxResult.success(result);
        }

        bizPayOrderService.insertBizPayOrder(payOrder);
        //微信支付
        String openid = request.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            return AjaxResult.warn("openid未获取");
        }

        try {
            result = PayUtil.preparePay(tradeNo, openid, money);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result == null) {
            return AjaxResult.warn("支付出现问题, 请联系管理员");
        }
        result.put("plat", "wx");
        return AjaxResult.success(result);
    }
}
